package com.cqut.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;

import com.alibaba.fastjson.JSONObject;
import com.cqut.service.IMenuService;
import com.cqut.model.Menu;
import com.cqut.dto.LimitShowDTO;
import com.cqut.util.ResponseUtil;
import com.cqut.util.StringUtil;
import com.cqut.validInterfaces.GroupForAdd;
import com.cqut.dto.MenuDTO;


@RestController
@RequestMapping("/api/menu")
public class MenuController {
    @Resource(name="menuService")
    private IMenuService menuService;

    /**
     * 初始化模块列表
     * @param limitShowDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public ResponseEntity<String> list(
    	@Validated
    	Menu menu,
        @Validated
        LimitShowDTO limitShowDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Map<String, Object> result = new HashMap<String, Object>();

        List<Map<String, Object>> menuList = menuService.getLoadList(menu,limitShowDTO);
        long count = menuService.getLoadListCount(menu,limitShowDTO);

        result.put("rows", menuList);
        result.put("total", count);

        return ResponseUtil.getResEntityForGetAndJson(result);
    }

    /**
     * 根据id查询模块详情
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/{menuId}", method = RequestMethod.GET)
    public ResponseEntity<String> show(@PathVariable("menuId") String menuId) {
        Map<String, Object> menuModel = menuService.findMap(menuId);

        return ResponseUtil.getResEntityForGetAndJson(menuModel);
    }

    /**
     * 新增模块
     * @param menuDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public ResponseEntity<String> create(
        @Validated
        MenuDTO menuDTO, BindingResult errors) {
        if(errors.hasErrors())
            return ResponseUtil.getResponseEntityWhenInvalidReqParams();

        Menu menuModel = menuDTO.toModel();

        return ResponseUtil.getResEntityForPPP(menuService.save(menuModel));
    }

    /**
     * 根据id更新模块
     * @param menuId
     * @param menuDTO
     * @param errors
     * @return
     */
    @RequestMapping(value = "/{menuId}", method = RequestMethod.PUT)
    public ResponseEntity<String> update(@PathVariable("menuId") String menuId,
        @Validated
        MenuDTO menuDTO, BindingResult errors) {

        Menu menuModel = menuDTO.toModel();
        menuModel.setMenuId(menuId);
        return ResponseUtil.getResEntityForPPP(menuService.update(menuModel));
    }

    /**
     * 根据id删除模块
     * @param menuId
     * @return
     */
    @RequestMapping(value = "/{menuId}", method = RequestMethod.DELETE)
    public ResponseEntity<String> destory(@PathVariable("menuId") String menuId) {
        return ResponseUtil.getResEntityForDel(menuService.delete(menuId));
    }

    /**
     * 根据id数组批量删除模块
     * @param primaryKeys
     * @return
     */
    @RequestMapping(value = "/deletes", method = RequestMethod.DELETE)
    public ResponseEntity<String> deletes(@RequestParam("primaryKeys") String[] primaryKeys) {
        return ResponseUtil.getResEntityForDel(menuService.batchDelete(primaryKeys));
    }
    
    /**
	 * 新增模块
	 */
	@RequestMapping(value="/addModule",method = RequestMethod.POST)
	public  ResponseEntity<String> addModule(
		@Validated(GroupForAdd.class)
		MenuDTO menuDTO,BindingResult errors){
		//如果有错
		if(errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		if(menuService.addModule(menuDTO)){
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		}
			
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
    
	/**
	 * 查找模块条数
	 */
	@RequestMapping(value="/findModulesWithLimit", method=RequestMethod.GET)
	public ResponseEntity<String> findModulesWithLimit(String moduleName,String parentCode) {
		JSONObject json = new JSONObject();
		json.put("total", menuService.findCountOfModules(moduleName,parentCode));
		
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
	
    /**
	 * 根据模块名称查询模块，无关层级
	 */
	@RequestMapping(value="/findModules", method=RequestMethod.GET)
	public ResponseEntity<String> findModules(
			String moduleName,	
			LimitShowDTO limitShowDTO, BindingResult errors) {
		
		if(errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		List<Map<String, Object>> modules = menuService.findModules(moduleName,limitShowDTO);
		
		return ResponseUtil.getResEntityForGetAndJsonArray(modules);
	}
	
	/**
	 * 搜索时统计模块数量
	 * @param moduleName
	 * @param limitShowDTO
	 * @param errors
	 * @return
	 */
	@RequestMapping(value="/searchModuleCount",method=RequestMethod.GET)
	public ResponseEntity<String> searchModuleCount(
			String moduleName,
			LimitShowDTO limitShowDTO, BindingResult errors
			){
		
		if(errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		JSONObject json = new JSONObject();
		json.put("total", menuService.searchModuleCount(moduleName,limitShowDTO));
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
	/**
	 * 新增时判断模块名是否重复
	 * */
	@RequestMapping(value = "/validationDate", method = RequestMethod.POST)
	public ResponseEntity<String> judgeRepition(String validationDate) {
		if (StringUtil.isNullOrEmpty(validationDate))
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		
		JSONObject json = new JSONObject();
		json.put("state", menuService.judgeRepition(validationDate));
		
		return ResponseUtil.getResEntityForGet(json.toJSONString());
	}
    
	
	/**
	 * 模块上移
	 */
	@RequestMapping(value="/moveUp",method = RequestMethod.PUT)
	public ResponseEntity<String> moveUp(
			int orderNo,
			String menuId,
			String upId){
		
		//如果有错
		if(orderNo < 0 || StringUtil.isNullOrEmpty(menuId))
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		if(menuService.moveUp(orderNo,menuId,upId))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
	
	/**
	 * 模块下移
	 */
	@RequestMapping(value="/moveDown",method = RequestMethod.PUT)
	public ResponseEntity<String> moveDown(
			int orderNo,
			String menuId,
			String upId){
		
		//如果有错
		if(orderNo < 0 || StringUtil.isNullOrEmpty(menuId))
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		if(menuService.moveDown(orderNo,menuId,upId))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
	
	/**
	 * 进入下一级目录
	 */
	@RequestMapping(value="/goNextCatalog",method = RequestMethod.GET)
	public ResponseEntity<String> geNextCatalog(
			String parentCode,
			LimitShowDTO limitShowDTO, BindingResult errors){
		
		return ResponseUtil.getResEntityForGetAndJsonArray(menuService.goNextCatalog(parentCode, limitShowDTO));
	}
	
	/**
	 * 通过menuId获取在menu表中获取一条对应的数据
	 * @return
	 */
	@RequestMapping(value="/getModuleObjectById",method=RequestMethod.GET)
	public ResponseEntity<String> getModuleObjectById(	
			String menuId
			){
		Map<String,Object> data = menuService.getModuleObjectById(menuId);
		return ResponseUtil.getResEntityForGetAndJson(data);
	}
	
	/**
	 * 通过menuId删除模块以及它的所有子模块
	 * @return
	 */
	@RequestMapping(value="/deleteByIdsAndChild",method=RequestMethod.POST)
	public ResponseEntity<String> deleteByIdsAndChild(
			@RequestParam("menuIdList")
			String[] menuIdList){
		if(menuIdList == null || 0 == menuIdList.length)
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		if(menuService.deleteByIdsAndChild(menuIdList))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
			
		return ResponseUtil.getResEntityForPPPWhenFail();
	}
	
	/**
	 * 修改
	 * @param menuDTO
	 * @param errors
	 * @return
	 */
	@RequestMapping(value="/updateModuleObject",method=RequestMethod.PUT)
	public ResponseEntity<String> updateModuleObject(
			Menu menu,BindingResult errors
			){
		if(errors.hasErrors())
			return ResponseUtil.getResponseEntityWhenInvalidReqParams();
		if(menuService.updateModuleObject(menu))
			return ResponseUtil.getResEntityForPPPWhenSuccess();
		
		return ResponseUtil.getResEntityForPPPWhenFail();
		
	}
}
